package org.example.user.controller.User;

import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Base.Result;
import org.example.friend.service.FriendService;
import org.example.user.entity.User;
import org.example.user.entity.UserContext;
import org.example.user.service.User.UserService;
import org.example.util.FileSetUtil;
import org.example.util.JWTUtil;
import org.example.util.MD5Util;
import org.example.util.OssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Validated
@RestController
@RequestMapping("/user")
@EnableFeignClients(basePackages = "com.example.client.service")
public class UserController {
    private final UserService userService;
    private final FriendService friendService;

    public UserController(UserService userService, FriendService friendService) {
        this.userService = userService;
        this.friendService = friendService;
    }

    @PostMapping("/register")
    public Result register(@RequestBody Map<String, String> body){
        //获取当前时间
        String UserName=body.get("UserName");
        String UserEmail=body.get("UserEmail");
        String UserPassWord=body.get("UserPassWord");
        int UserAge=Integer.parseInt(body.get("UserAge"));
        String UserSex=body.get("UserSex");
        String UserFrom=body.get("UserFrom");
        String dept=body.get("deptid");
        Long deptid = Long.parseLong(dept);
        LocalDateTime now = LocalDateTime.now();
        String UserRegisterTime=now.toString();
        //查询用户名是否被占用
        //查询该邮箱是否已注册
        User user=new User(UserName,UserEmail,UserPassWord,UserAge,UserSex,UserFrom,UserRegisterTime,0,deptid);
        User u = userService.findUserByNameorEmail(user);
        if(u==null){//未被占用
            //注册
            userService.register(UserName,UserEmail,UserPassWord,UserAge,UserSex,UserFrom,UserRegisterTime,deptid);
                return Result.success(user);
            }
        else {
            return  Result.error("用户名已被占用");
        }
    }
    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> body, HttpServletResponse response){//@Pattern(regexp="^\\s{5,16}$")
        //根据用户邮箱查询用户
        String UserEmail=body.get("UserEmail");
        String UserPassWord=body.get("UserPassWord");
        User loginUser=userService.findUserByEmail(UserEmail);
        System.out.println(loginUser);
        if (loginUser==null){
            return Result.error("邮箱未注册或邮箱填写错误");
        }
        if (MD5Util.string2MD5(UserPassWord).equals(loginUser.getUserPassWord())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("Email", loginUser.getUserEmail());
            claims.put("Name", loginUser.getUserName());

            String token = JWTUtil.genToken(claims);
            UserContext.setUser("账号" + loginUser.getUserEmail() + "，用户名" + loginUser.getUserName());
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }
    @PostMapping("/remanlogin")
    public Result remanlogin(@RequestBody Map<String, String> body, HttpServletResponse response){//@Pattern(regexp="^\\s{5,16}$")
        //根据用户邮箱查询用户
        String UserEmail=body.get("UserEmail");
        String UserPassWord=body.get("UserPassWord");
        User loginUser=userService.findUserByEmail(UserEmail);
        System.out.println(loginUser);
        if (loginUser==null){
            return Result.error("邮箱未注册或邮箱填写错误");
        }
        if (MD5Util.string2MD5(UserPassWord).equals(loginUser.getUserPassWord())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("Email", loginUser.getUserEmail());
            claims.put("Name", loginUser.getUserName());

            String token = JWTUtil.genToken(claims);
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            UserContext.setUser("账号" + loginUser.getUserEmail() + "，用户名" + loginUser.getUserName());
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }
    @GetMapping("/getMySelf")
    public Result getMySelf(HttpServletRequest request){
         String token=request.getHeader("Authorization");
         Map<String,Object> c=JWTUtil.parseToken(token);
         String Email=(String)(c.get("Email"));//Email为用户邮箱
        System.out.println(Email);
        User user=userService.getMySelf(Email);
        return Result.success(user);
    }
    @PostMapping("/postMyPictrue")
    public Result postMyPictrue(HttpServletRequest request,MultipartFile Picture){
        File file =  FileSetUtil.saveFile(Picture,"./external-resources/", LocalTime.now().toString());
        String imageurl= OssUtil.uploadImage(file.getName());
          String token=request.getHeader("Authorization");
        Map<String,Object> c=JWTUtil.parseToken(token);
        String Email=(String)(c.get("Email"));//Email为用户邮箱
        User user=userService.findUserByEmail(Email);
        user.setUserPicture(imageurl);
          userService.updataUser(user);
          return Result.success();
    }

    //获取全部用户
    @GetMapping("/list")
    public Result<PageInfo> List(@RequestParam(name="PageNumber", defaultValue = "1")int PageNumber, @RequestParam(name="PageSize", defaultValue = "5")int PageSize){
        PageInfo<User> UserList=userService.getUserList(PageNumber,PageSize);
        return  Result.success(UserList);
    }

    //管理员登录
    @PostMapping("/adminlogin")
    public Result adminlogin(@RequestBody Map<String, String> body, HttpServletResponse response){//@Pattern(regexp="^\\s{5,16}$")
        //根据用户邮箱查询用户
        String UserEmail=body.get("UserEmail");
        String UserPassWord=body.get("UserPassWord");
        User loginUser=userService.findUserByEmailAndPower(UserEmail);
        System.out.println(loginUser);
        System.out.println(loginUser.getPower());
        if(loginUser.getPower()!=0 && loginUser.getPower()!=2){
            return Result.error("权限不足");
        }
        if (loginUser==null){
            return Result.error("邮箱未注册或邮箱填写错误");
        }
        if (MD5Util.string2MD5(UserPassWord).equals(loginUser.getUserPassWord())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("Email", loginUser.getUserEmail());
            claims.put("Name", loginUser.getUserName());
            String token = JWTUtil.genToken(claims);
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }
    //修改用户
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody Map<String, String> body){
        System.out.println(body);
        User user=userService.findUserByEmail(body.get("UserEmail"));
        System.out.println(body.get("UserEmail"));
        String UserPassWord=body.get("UserPassWord");
        if(UserPassWord!=null){
            UserPassWord=MD5Util.string2MD5(UserPassWord);
            user.setUserPassWord(UserPassWord);
        }
        int UserAge=Integer.parseInt(body.get("UserAge"));
        if(UserAge!=0){
            user.setUserAge(UserAge);
        }
        String UserSex=body.get("UserSex");
        if(UserSex!=null){
            user.setUserSex(UserSex);
        }
        String UserFrom=body.get("UserFrom");
        if(UserFrom!=null){
            user.setUserFrom(UserFrom);
        }
        String newUserName = body.get("UserName");
        if(newUserName!=null){
            user.setUserName(newUserName);
        }
        System.out.println(user.getUserSex()+user.getUserAge()+user.getUserPassWord()+user.getUserFrom()+user.getUserName());
        userService.updateUser(user);
        return Result.success();
    }
    //修改密码
    @PostMapping("/updatePassWord")
    public Result updatePassWord(@RequestParam String Email,@RequestParam String UserPassWord){
        User user=userService.findUserByEmail(Email);
        if(UserPassWord!=null){
            UserPassWord=MD5Util.string2MD5(UserPassWord);
            user.setUserPassWord(UserPassWord);
            userService.updateUser(user);
        }
        return Result.success();
    }
    //删除用户
    @DeleteMapping ("/deleteUser")
    public Result deleteFriend(HttpServletRequest request,@RequestBody Map<String, String> body){
        String token=request.getHeader("Authorization");
        Map<String, Object> c= JWTUtil.parseToken(token);
        String Email=(String)(c.get("Email"));
        User user=userService.findUserByEmail(body.get("UserEmail"));
        //找好友
        //userService.deleteUser(Email,friendEmail,);
        return Result.success("删除成功");
    }
    @GetMapping("/userl")
    public List userl(){
        List UserList=userService.userl();
        return  UserList;
    }
    @GetMapping("/getUserInfo")
    public String getUserInfo(@RequestParam String userEmail) {
        return userService.getUserInfo(userEmail);
    }

    @GetMapping("/getUserPicture")
    public String getUserPicture(@RequestParam String userEmail) {
        return userService.getUserPicture(userEmail);
    }
}
